package com.aistar.service.impl;

import com.aistar.mapper.FlowMapper;
import com.aistar.mapper.OrdersMapper;
import com.aistar.pojo.*;
import com.aistar.service.*;
import com.aistar.util.ServerResponse;
import com.aistar.util.alipay.OrderStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private FlowMapper flowMapper;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private OrderDetailsService orderDetailsService;

    @Autowired
    private ProductService productService;

    //添加
    @Override
    public ServerResponse save(Orders order) {
        int rows = ordersMapper.insert(order);
        if (rows>0){
            return ServerResponse.addSuccess();
        }else {
            return ServerResponse.addFailed();
        }
    }

    @Override
    public ServerResponse modifyStatus(Orders order) {
        return null;
    }

    @Override
    public ServerResponse modify(Orders order) {
        return null;
    }

    //根据订单id 获取到订单对象
    @Override
    public ServerResponse getById(Integer id) {
        Orders order = ordersMapper.selectByPrimaryKey(id);
        if (order != null){
            return ServerResponse.getDataSuccess(order);
        }else {
            return ServerResponse.getDataFailed("service没有此订单");
        }
    }

    @Override
    public ServerResponse getAll() {
        return null;
    }

    //根据订单编号将订单id查询出来
    @Override
    public ServerResponse getOrderByOrderNum(String num) {
        OrdersExample ordersExample = new OrdersExample();
        ordersExample.createCriteria().andOrderNumberEqualTo(num)
                .andOrderStatusEqualTo(1);
        List<Orders> ordersList = ordersMapper.selectByExample(ordersExample);
        if (ordersList !=null && ordersList.size()>0){
            return ServerResponse.getDataSuccess(ordersList);
        }else {
            return ServerResponse.getDataFailed("查询失败");
        }

    }

    //修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
    @Override
    public void updateOrderStatus(Integer orderId, String alpayFlowNum, String paidAmount) {
        //根据订单id查询到订单对象
        Orders order = (Orders) getById(orderId).getData();
        System.out.println("进入到生成流水的页面");
        if (order.getPayStatus().equals(OrderStatusEnum.WAIT_PAY.key)){
            order = new Orders();
            order.setOrderId(orderId);
            order.setPayStatus(OrderStatusEnum.PAID.key);
            //先修改订单状态
            //订单的支付时间没做
            ordersMapper.updateByPrimaryKeySelective(order);
            order = (Orders) getById(orderId).getData();

            String flowId = UUID.randomUUID().toString().replace("-","");
            Flow flow = new Flow();
            flow.setId(flowId);
            flow.setFlowNum(alpayFlowNum);
            flow.setCreateTime(new Date());
            flow.setOrderNum(order.getOrderNumber());
            flow.setPaidAmount(paidAmount);
            flow.setPaidMethod(1);
            flow.setFlowStatus(1);
            //添加流水
            flowMapper.insertSelective(flow);

        }

    }

    //根据用户id 查询出该用户所有的
    @Override
    public ServerResponse getAllByCustomerId(Integer customerId) {
       OrdersExample ordersExample = new OrdersExample();
       ordersExample.createCriteria().andOrderStatusEqualTo(1)
               .andCustomerIdEqualTo(customerId).andAddressIdIsNotNull();
       List<Orders> ordersList = ordersMapper.selectByExample(ordersExample);
       if (ordersList != null && ordersList.size()>0){
           return ServerResponse.getDataSuccess(ordersList);
       }else {
           return ServerResponse.getDataFailed("该用户没有订单");
       }

    }


    //根据用户id 查询出改用胡的订单详情记录 地址等等 封装到一个vo对象中
    @Override
    public ServerResponse getAllOrderByCustomerId(Integer customerId) {
        /*OrdersProductVo ordersProductVo =  new OrdersProductVo();
        List<OrdersProductVo> voList = new ArrayList<>();
        ServerResponse sr = getAllByCustomerId(customerId);
        List<Product> productList = new ArrayList<>();
        if (sr.getStatus() ==1){
            //表示有数据
            List<Orders> ordersList = (List<Orders>) sr.getData();
            //循环orderList 分别拿到对应的ordersId（查询详情表用到），addressId（查询地址）,
            //customerId（查询用户）
            for (Orders order:ordersList){
                Customer customer = (Customer) customerService.getById(order.getCustomerId()).getData();
                List<Address> addressList = (List<Address>) addressService.getById(order.getAddressId()).getData();
                Address address = addressList.get(0);

                List<OrderDetails> orderDetailsList = (List<OrderDetails>) orderDetailsService.getOrderDetailsByOrderId(order.getOrderId()).getData();

                //再次循环将商品di取出
                for (OrderDetails orderDetails:orderDetailsList){
                    Product product = (Product) productService.getById(orderDetails.getProductId()).getData();
                    productList.add(product);
                }
                ordersProductVo.setOrderDetailsList(orderDetailsList);
                ordersProductVo.setAddress(address);
                ordersProductVo.setProductList(productList);
                voList.add(ordersProductVo);
            }


            return ServerResponse.getDataSuccess(voList);
        }else {
            return ServerResponse.getDataFailed("查询失败");
        }*/
        return null;

    }

    //根据用户id获取到orde人(多) 地址信息 不分页
    @Override
    public ServerResponse getOrderAndAddressByCustomerId(Integer customerId) {
        List<OrderAddressVo> orderAddressVoList = new ArrayList<>();
        ServerResponse sr = getAllByCustomerId(customerId);
        if (sr.getStatus() ==1) {
            //表示有数据
            List<Orders> ordersList = (List<Orders>) sr.getData();
            //循环orderList 分别拿到对应的ordersId（查询详情表用到），addressId（查询地址）,
            //customerId（查询用户）
            for (Orders order:ordersList){
                Customer customer = (Customer) customerService.getById(order.getCustomerId()).getData();
                List<Address> addressList = (List<Address>) addressService.getById(order.getAddressId()).getData();
                Address address = addressList.get(0);
                OrderAddressVo orderAddressVo = new OrderAddressVo();
                orderAddressVo.setAddress(address);
                orderAddressVo.setOrders(order);
                orderAddressVoList.add(orderAddressVo);
            }
            return ServerResponse.getDataSuccess(orderAddressVoList);
        }else {
            return ServerResponse.getDataFailed("查询失败");
        }
    }
}
